package com.itheima.Controller;

import com.itheima.Service.UserService;
import com.itheima.pojo.Permission;
import com.itheima.pojo.Result;
import com.itheima.pojo.User;
import com.itheima.pojo.UserLogin;
import com.itheima.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@Slf4j
@RequestMapping("/api")
public class LoginController {
    @Autowired
    private UserService userService;
    private User loginUser;

    @PostMapping("/login")
    private Result login(@RequestBody User user) {
        log.info("调用登录接口:{}", user);
        User u = userService.login(user);
        //登录成功生成令牌
        if (u != null) {
            Map<String, Object> claims = new HashMap<>();
            claims.put("id", u.getId());
            claims.put("name", u.getUsername());
            claims.put("phoneNumber", u.getPhoneNumber());
            String jwt = JwtUtils.generateJwt(claims);
            if (u.getIsEnabled() == 0) {
                return Result.Error("该账户未启用");
            }
            this.loginUser = u;
            return Result.success(jwt);
        }

        return Result.Error("用户名或密码错误");
    }

    /*
     *   获取登录用户信息
     * */
    @GetMapping("/info")
    private Result getInfo() {
        log.info("调用获取已登录资料");
        List<Permission> permissions = userService.getPersmissions(loginUser.getRoleId());
        User user = userService.getUserById(loginUser.getId());
        user.setPermissions(permissions);
        return Result.success(user);
    }
}
